package com.appspot.moviesessions.provider;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.appspot.moviesessions.EventListener;
import com.appspot.moviesessions.EventPublisher;

public class DatabaseAdapter implements Database {

	private SQLiteOpenHelper sqlLiteOpenHelper;

	public DatabaseAdapter(SQLiteOpenHelper helper, EventPublisher publisher) {
		this.sqlLiteOpenHelper = helper;
		publisher.register(new EventListener<DataFoundEvent>() {
			@Override
			public void onEvent(DataFoundEvent event) {
				switch (event.getType()) {
				case MOVIE:
					getDatabase().insert(MovieSession.Movie.TABLE, null,
							event.getValues());
					break;
				case LOCATION:
					getDatabase().insert(MovieSession.Location.TABLE, null,
							event.getValues());
					break;
				case SESSION:
					getDatabase().insert(MovieSession.Session.TABLE, null,
							event.getValues());
					break;
				default:
					break;
				}

			}
		});
	}

	@Override
	public Cursor query(QuerySpecification spec) {
		return getDatabase().query(spec.table, spec.getColumns(),
				spec.selection, spec.getSelectionArgs(), spec.groupBy,
				spec.having, spec.orderBy);
	}

	@Override
	public void execSQL(String sql) {
		getDatabase().execSQL(sql);
	}

	@Override
	public Cursor rawQuery(String query, String[] selectionArgs) {
		return getDatabase().rawQuery(query, selectionArgs);
	}

	@Override
	public long insert(String table, ContentValues values) {
		return getDatabase().insert(table, null, values);
	}

	private SQLiteDatabase getDatabase() {
		return sqlLiteOpenHelper.getWritableDatabase();
	}

}
